package dbgroup02.dao.db2;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import dbgroup02.bean.FlightTicket;
import dbgroup02.dao.FlightTicketDao;

public class FlightTicketDB2Dao implements FlightTicketDao {

	private JdbcTemplate jdbcTemplate;

	ParameterizedRowMapper<FlightTicket> getFlightTicketMapper = new ParameterizedRowMapper<FlightTicket>() {
		@Override
		public FlightTicket mapRow(ResultSet resultSet, int arg1)
				throws SQLException {
			FlightTicket flightTicket = new FlightTicket();
			flightTicket.setIdFlightTicket(resultSet.getInt(1));
			flightTicket.setIdFlight(resultSet.getInt(2));
			flightTicket.setIdBoardingPass(resultSet.getInt(3));
			flightTicket.setIdMeal(resultSet.getInt(4));
			flightTicket.setIdClass(resultSet.getInt(5));
			flightTicket.setIdTicket(resultSet.getInt(6));
			return flightTicket;
		}
	};

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	@Override
	@Transactional(readOnly = true, propagation = Propagation.REQUIRED)
	public FlightTicket getFlightTicket(int idFlightTicket) {
		List<FlightTicket> result = jdbcTemplate.query("SELECT * FROM "
				+ FlightTicketDao.SCHEMA
				+ ".FLIGHT_TICKET WHERE FLIGHT_TICKET_ID = ?",
				new Object[] { idFlightTicket }, getFlightTicketMapper);

		if (result.size() > 0)
			return result.get(0);
		else
			return null;
	}

	@Override
	@Transactional(readOnly = true, propagation = Propagation.REQUIRED)
	public List<FlightTicket> getFlightTickets(int idTicket) {
		List<FlightTicket> result = jdbcTemplate.query(
				"SELECT * FROM " + FlightTicketDao.SCHEMA
						+ ".FLIGHT_TICKET WHERE TICKET_ID = ?",
				new Object[] { idTicket }, getFlightTicketMapper);

		return result;
	}

	@Override
	@Transactional(readOnly = true, propagation = Propagation.REQUIRED)
	public void updateFlightTicket(FlightTicket flightTicket) {
		jdbcTemplate
				.update("UPDATE "
						+ SCHEMA
						+ ".FLIGHT_TICKET SET FLIGHT_ID = ?,	BOARDING_PASS_ID = ?, MEAL_ID = ?, CLASS_ID = ?, TICKET_ID = ? WHERE FLIGHT_TICKET_ID = ?",
						new Object[] { flightTicket.getIdFlight(),
								flightTicket.getIdBoardingPass(),
								flightTicket.getIdMeal(),
								flightTicket.getIdClass(),
								flightTicket.getIdTicket(),
								flightTicket.getIdFlightTicket() });
	}

}
